<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Exception;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Admin as ModelAdmin;
use Hangpu888\Hpadmin\model\AdminRole;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\UploadsManager;
use Hangpu888\Hpadmin\validate\Admin as ValidateAdmin;
use Shopwwi\WebmanFilesystem\Facade\Storage;

class Admin extends Controller
{
    /**
     * 显示列表
     *
     * @return void
     */
    public function index()
    {
        $limit = request()->get('limit',30);
        $page = request()->get('page',1);
        $status = ['禁用', '正常'];
        $list = ModelAdmin::with(['role'])
        ->order('id desc')
        ->paginate([
            'page'          => $page,
            'list_rows'     => $limit
        ])
        ->each(function($item)use($status){
            if ($item->headimg) {
                $item->headimg = Storage::url($item->headimg);
            }
            $item->status_text = $status[$item->status];
            $item->admin_role = $item->role->title;
            $item->last_login_ip = $item->last_login_ip;
            $item->last_login_time = $item->last_login_time;
            // 系统管理员禁止删除
            $item->btnAttr = [
                'edit'      => [
                    'show'  => $item->role->is_system ? false : true
                ],
                'delete'    => [
                    'show'  => $item->role->is_system ? false : true
                ],
            ];
            return $item;
        })
        ->toArray();
        $builder = new ListBuilder;
        $data = $builder
            ->addColumn('rightButtonList', '操作', [
                'type'              => 'template',
                'template'          => 'rightButtonList',
                'width'             => '180'
            ])
            ->addTopButton('add', '添加', [
                'title'             => '添加数据',
                'api'               => '/hpadmin/Admin/add',
            ])
            ->addRightButton('edit', '修改', [
                'api'               => '/hpadmin/Admin/edit',
                'title'             => '修改',
            ], [
                'type'              => 'text'
            ])
            ->addRightButton('delete', '删除', [
                'api'               => '/hpadmin/Admin/del',
                'method'            => 'delete',
                'title'             => '温馨提示',
                'content'           => '是否确认删除该数据？',
                'type'              => 'confirm',
            ], [
                'type'              => 'text',
            ])
            ->addColumn('id', '序号', [
                'width'             => '80',
            ])
            ->addColumn('ctime', '添加时间', [
                'width'             => '180',
            ])
            ->addColumn('admin_role', '所属角色')
            ->addColumn('headimg', '头 像', [
                'type'              => 'image',
            ])
            ->addColumn('username', '账 号')
            ->addColumn('nickname', '昵 称')
            ->addColumn('status_text', '状 态', [
                'width'             => '100'
            ])
            ->addColumn('last_login_ip', '最近登录IP')
            ->addColumn('last_login_time', '最近登录')
            ->setData($list['data'])
            ->setDataPage($list['total'], $list['last_page'], $list['per_page'], $list['current_page'])
            ->create();
        return Json::successRes($data);
    }


    /**
     * 添加/显示视图
     *
     * @return void
     */
    public function add()
    {
        try {
            if (request()->method() == 'POST') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateAdmin,$post,'form');
                
                // 拼接数据
                $uploadManager = new UploadsManager;
                $post['imgurl'] = $uploadManager->strReplaceUrl($post['imgurl']);
                $post['password'] = md5($post['password']);
                $adminModel = new ModelAdmin;
                foreach ($post as $field => $value) {
                    $adminModel->$field = $value;
                }
                if ($adminModel->save()) {
                    return Json::success('添加成功');
                } else {
                    return Json::fail('添加失败');
                }
            } else {
                $roleModel = new AdminRole;
                $roleList = $roleModel->getRoleOptions();
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('post')
                    ->addRow('role_id', 'select', '所属角色', '', [
                        'options'           => $roleList,
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('status', 'radio', '当前状态', 1, [
                        'options'           => [
                            [
                                'label'     => '锁定',
                                'value'     => 0,
                            ],
                            [
                                'label'     => '正常',
                                'value'     => 1,
                            ],
                        ],
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('nickname', 'input', '用户昵称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('headimg', 'custom', '账号头像', '', [
                        'type'              => 'uploadify',
                        'extra'             => [
                            'props'         => [
                                'format'    => 'image',
                                'btn_text'  => '选择头像',
                                'limit'     => 1,
                                'ext'       => 'jpg,png,gif',
                                'width'     => 300,
                                'height'    => 300,
                            ],
                            'col'           => [
                                'span'      => 12
                            ],
                        ],
                    ])
                    ->addRow('username', 'input', '登录账号', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('password', 'input', '登录密码', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 编辑/视图
     *
     * @return void
     */
    public function edit()
    {
        try {
            $id = request()->get('id');
            if (request()->method() == 'PUT') {
                // 获取数据
                $post = request()->post();
                $adminModel = ModelAdmin::where(['id' => $id])->find();
                if (!$adminModel) {
                    return Json::fail('数据不存在');
                }
                if (isset($post['password']) && !empty($post['password'])) {
                    $post['password'] = md5($post['password']);
                }else{
                    unset($post['password']);
                }
                if (isset($post['headimg']) && !empty($post['headimg'])) {
                    $uploadManager = new UploadsManager;
                    $post['imgurl'] = $uploadManager->strReplaceUrl($post['imgurl']);
                }
                foreach ($post as $field => $value) {
                    $adminModel->$field = $value;
                }
                if ($adminModel->save()) {
                    return Json::success('修改成功');
                } else {
                    return Json::fail('修改失败');
                }
            } else {
                $response = ModelAdmin::where(['id' => $id])->find();
                if (!$response) {
                    return Json::fail('该数据不存在');
                }
                $response = $response->toArray();
                $response['headimg'] = Storage::url($response['headimg']);
                $response['password'] = '';
                $roleModel = new AdminRole;
                $roleList = $roleModel->getRoleOptions();
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('put')
                    ->addRow('role_id', 'select', '所属角色', '', [
                        'options'       => $roleList,
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('status', 'radio', '当前状态', 1, [
                        'options'       => [
                            [
                                'label' => '锁定',
                                'value' => 0,
                            ],
                            [
                                'label' => '正常',
                                'value' => 1,
                            ],
                        ],
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('nickname', 'input', '用户昵称', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('headimg', 'custom', '账号头像', '', [
                        'type'              => 'uploadify',
                        'extra'             => [
                            'props'         => [
                                'format'    => 'image',
                                'btn_text'  => '选择头像',
                                'limit'     => 1,
                                'ext'       => 'jpg,png,gif',
                            ],
                            'col'               => [
                                'span'          => 12
                            ],
                        ],
                    ])
                    ->addRow('username', 'input', '登录账号', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('password', 'input', '登录密码', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->setFormData($response)
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 删除
     *
     * @return void
     */
    public function del()
    {
        $id = request()->get('id');
        $adminModel = ModelAdmin::where(['id' => $id])->find();
        if (!$adminModel) {
            return Json::fail('该数据不存在');
        }
        $roleModel = AdminRole::where(['id'=> $adminModel->role_id])->find();
        if ($roleModel->is_system) {
            throw new Exception('系统级别管理员禁止删除');
        }
        if ($adminModel->delete()) {
            return Json::success('删除成功');
        } else {
            return Json::fail('删除失败');
        }
    }
}
